<?php
namespace Home\Controller;
use Think\Cache\Driver\Redis;
use Think\Controller;

class GoodController extends Controller
{
    public function _initialize() {
        $this->theme(C('NOW_THEME'));
        $this->assign('theme', C('NOW_THEME'));
    }

    public function agentgoods()
    {
        //是否为代理
        $is_agent = M('agent')->where( array('agent_id'=>session('user_id')) )->getField('is_agent');
        if($is_agent !== "1"){
            $is_agent = 2;
        }

        //过滤条件
        $sort = I('get.sort');
        $price = I('get.price');
        $cate_id = to_int(I('get.id'));


        $sale = I('get.sale');
        //新品优先
        $new = I('get.new');
        if ($new == 1) {$order_by = 'id DESC';}
        //价格
        if ($price == 'reduce') {
            $order_by = 'price DESC';
        } elseif ($price == 'plus') {
            $order_by = 'price ASC';
        }
        //销量
        if ($sale == 'reduce') {
            $order_by = 'sale_num DESC';
        } elseif($sale == 'plus') {
            $order_by = 'sale_num ASC';
        }
        //综合排序
        $ranking = I('get.ranking');
        if ($ranking == 1) {
            $order_by = 'sale_num DESC,price DESC,id DESC';//销量高，价格便宜，发布较新
        }

        //品牌
        $brand_id = I('get.brand_id');

        if ($is_agent == 1 && empty($brand_id)) {
            $brandid = M('agent_brand')->where(array('agent_id' => session('user_id')))->select();
            foreach ( $brandid as $val) {
                $brandida[] = $val['brand_id'];
            }
            $n_agent_brands = M('brand')->where('agent_brand = 0')->field("id")->select();
            foreach($n_agent_brands as $n_b){
                $brandida[] = $n_b["id"];
            }
            $map['brand_id'] = array('in',$brandida);
        } else {
            if(! empty($brand_id)) $map['brand_id'] = $brand_id;
        }


        if (!empty($cate_id) && isset($cate_id)) {
            $map['cate'] = $cate_id;
        }
        //搜索
        $map['shelves'] = 1;

        $good = M('good')->where($map)->limit(6)->order($order_by)->select();
        //echo M('good')->getLastSql();
        $goods = get_unit_amt($good);
        $mName = trim(I('get.mName'));

        $this->assign('visitor',session('user_id'));

        if (!empty($mName)) {
            $map['g_name'] = array('like',"%$mName%");
            $good = M('good')->where($map)->order($order_by)->select();
            $goods = get_unit_amt($good);
            $keywords = trim(I('mName'));
            if ($keywords != '') {
                foreach($goods as $key=>$value){
                    if(strstr($value['g_name'],$keywords)!==false){
                        $goodss[] = $value;
                    }
                }
            }
            $this->assign('agentgoods',$goodss);
            $this->assign('agentgoods2',$goodss);
        } else {
            $this->assign('agentgoods',$goods);
            $this->assign('agentgoods2',$goods);
        }
        //获取代理商代理的所有的品牌
        $shop_id = session('reception_shopid');
        if ($is_agent == 1) {
            $brands = M('agent_brand')->alias('a')
                ->field('a.brand_id,b.b_name')
                ->join('LEFT JOIN __BRAND__ b ON a.brand_id=b.id')
                ->where(array('a.agent_id'=>session('user_id'),array('b.status'=>1, 'b.shop_id'=>$shop_id)))
                ->select();

        } else {
            $brands = M('brand')->field('id as brand_id,b_name')->where( array('status'=>1,'agent_brand'=>0,'b.shop_id'=>$shop_id) )->select();

        }

        //分类名称
        $c_name = M('category')->where( array('id'=>I('get.id')) )->getField('c_name');
        $this->assign('c_name', $c_name);
        $this->assign('model', I('get.model'));
        $this->assign('sort', $sort);
        $this->assign('id',to_int(I('get.id')));
        $this->assign('brands',$brands);
        $this->assign('price', $price);
        $this->assign('brand_id', $brand_id);
        $this->assign('ranking', $ranking);
        $this->assign('sale', $sale);
        $this->assign('new', I('get.new'));
        $this->assign('params' ,get_url_params());
        $this->assign('is_agent', $is_agent);
        $this->site_title = "商品列表";
        $this->display();
    }

    //分类页面
    public function cate()
    {
        $category = M('category')->where( array('status'=>1) )->order('sort ASC')->select();
        $map['shop_id'] = session('url_shop_id');
        $map['end_shelves'] = 1;
        if (IS_POST) {
            $m_name = trim(I('post.m_name'));
            $cate_id = I('post.cate_id');
            $map['cate'] = $cate_id;
            $map['shelves'] = 1;


            if (!empty($m_name)) {
                $map['g_name'] = array('like',"%$m_name%");
            }

            $good = M('good')->field('id, g_name, thumb, price')->where($map)->select();
            $this->assign('good', $good);
            $this->display('ajax_cate');
        } else {

            $map['cate'] = $category[0]['id'];
            $map['shelves'] = 1;

            $good = M('good')->field('id, g_name, thumb, price')->where($map)->select();
            $this->assign('cate_id', $category[0]['id']);
            $this->assign('categories', $category);
            $this->assign('good', $good);
            $this->site_title="商品分类";
            $this->display();
        }
    }

    public function moreagent()
    {
        $params = I("post.params");
        $where = pre_params($params);
        if(!empty($where['id'])){
            $map['cate'] = $where['id'];
        }

        if(!empty($where['mName'])){
            $map['g_name'] = array("like", "%{$where['mName']}%");
        }


        $is_agent = M('agent')->where( array('agent_id'=>session('user_id')) )->getField('is_agent');
        if ($is_agent == 1 && empty($where['brand_id'])) {//代理并且是有品牌参数过来
            $brandid = M('agent_brand')->where(array('agent_id'=>session('user_id')))->select();
            foreach ( $brandid as $key=>$val) {
                $brandida[$key]=$val['brand_id'];
            }
            $n_agent_brands = M('brand')->where('agent_brand = 0')->field("id")->select();
            foreach($n_agent_brands as $n_b){
                $brandida[] = $n_b["id"];
            }
            $map['brand_id'] = array('in',$brandida);
        } else {
            if(! empty($where['brand_id'])) $map['brand_id'] = $where['brand_id'];
        }



        if(!empty($where['price'])) {
            $order_by = ($where['price'] == 'reduce') ? 'price DESC' : 'price ASC';
        }

        //销量
        if(!empty($where['sale'])) {
            $order_by = ($where['sale'] == 'reduce') ? 'sale_num DESC' : 'sale_num ASC';
        }

        if ($where['ranking'] == 1) {
            $order_by = 'sale_num DESC,price DESC,id DESC';
        }
        if ($where['new'] == 1) {
            $order_by = 'id DESC';
        }
        $pageSize = 6;
        $page = $_POST['page'] ? to_int(I("post.page")) : 1;
        $pageB = ($page - 1) * $pageSize;
        $map['shelves'] = 1;
        $good = M('good')->where($map)->limit($pageB ,$pageSize)->order($order_by)->select();
        //echo M('good')->getLastSql();
        $goods = get_unit_amt($good);
        if(empty($goods)){
            echo 1;
        } else{
            $this->assign('agentgoods',$goods);
            $this->assign('agentgoods2',$goods);
            $model = I('post.model');
            if ($model == 2) {
                $this->display('moreagent_b');
            } else {
                $this->display('moreagent_a');
            }
        }
    }
    //商家商品列表
    public function businessgoods()
    {
//        读取菜单名称
        $category = get_category();
//        搜索
        if (isset($_REQUEST['mName']) || isset($_REQUEST['id'])){
            $cate_id = I('get.id');
            $mName = trim(I('get.mName'));
            if($cate_id != ''){
                $where['cate'] = $cate_id;
                $cate = M('category')->where(array('id'=>$cate_id))->find();
                $this->site_title=$cate['c_name'];
            }
            if($mName != ''){
                $cWhere['g_name'] = array("like", "%$mName%");
                $cWhere['price'] = array("eq", $mName);
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
        }else{
            $this->site_title = "商品列表";
        }
//        读取商品信息
        $where['type'] = 2;
        $where['shelves'] = 1;
        $res = M('good')->where($where)->order('id DESC')->limit(0,10)
            ->select();
//        $this->site_title = "商品列表";
        $this->assign('params' ,get_url_params());
        $this->assign('categories', $category);
        $this->assign('businessgoods', $res);
        $this->display();
    }

    public function morebusiness()
    {
        $params = I("post.params");
        $param_where = pre_params($params);
        if(!empty($param_where['id'])){
            $where['cate'] = $param_where['id'];
            unset($param_where['id']);
        }
        $where['type'] = 2;
        $where['shelves'] = 1;
        $pageSize = 10;
        $page = $_POST['page'] ? to_int(I("post.page")) : 1;
        $pageB = ($page - 1) * $pageSize;
        if(!empty($param_where['mName'])){
            $mName = $param_where['mName'];
            unset($param_where['mName']);
            if ($mName != '') {
                $cWhere['g_name'] = array("like", "%$mName%");
                $cWhere['price'] = array("eq", $mName);
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
        }
        $res =M('good')->where($where)->order('id DESC')->limit($pageB, $pageSize)
            ->select();
        if(empty($res)){
            echo 1;
        }else{
            $this->assign('businessgoods',$res);
            $this->display();
        }
    }

    //商品详情
    public function goodsdetail()
    {
        //是否为代理
        $is_agent = M('agent')->where( array('agent_id'=>session('user_id')) )->getField('is_agent');
        if($is_agent !== "1"){
            $is_agent = 2;
        }

        $goodid = to_int(I('get.id'));
        $good = M('good')->where(array('id' => $goodid))->find();

        if ($good['end_shelves'] == -1 || $good['shelves'] == -1) {
            $this->error('此商品已下架');
        }


        $brand_id = $good['brand_id'];
        $res = M('agent_brand')->where(array('agent_id'=>session('user_id'),'brand_id'=>$brand_id))->find();

        //查询商品的规格和规格值
        $goodSpec = M('goodSpec')->alias('a')->field('a.good_id,b.s_name, a.spec_val')
            ->join('LEFT JOIN __SPEC__ b ON a.spec_id=b.id')
            ->where( array('a.good_id'=>$goodid) )->select();
        $spec = M('spec')->order('id ASC')->select();
        foreach ($goodSpec as $k=>$v) {
            $goodSpec[$k]['spec_val'] = explode(',', $goodSpec[$k]['spec_val']);
        }
        $c_name = M('category')->where(array('id'=>$good['cate']))->find();
        $b_name = M('brand')->where(array('id'=>$good['brand_id']))->find();
        $goodpic = M('good_pic')->where(array('good_id'=>$goodid))->select();
        //如果商品是代理商品的话
        if($b_name["agent_brand"] == 1){
            $rankprice= M('good_rank_price')->where(array('good_id'=>$goodid,'rank_id'=>$res['rank_id']))->find();
            $good['unit_amt']=$rankprice['unit_amt'];
            $good['batch_amt']=$rankprice['batch_amt'];
        }
        $status = "none";
        $self_address = M("agent_address")->where("state = 0 AND agent_id = %d",session("user_id"))->find();
        if($self_address){
            $status = "has";
        }
        $this->assign("self_address" ,$status);
        $this->assign('goodpic',$goodpic);
        $this->assign('b_name',$b_name['b_name']);
        $this->assign('agent_brand',$b_name["agent_brand"]);
        $this->assign('c_name',$c_name['c_name']);
        $this->assign('id',$goodid);
        $this->site_title = "详情列表";
        $this->assign('goodsdetail',$good);
        $this->assign('spec', $spec);
        $this->assign('goodSpec',$goodSpec);
        $this->assign("count_gs",count($goodSpec));
        $this->assign('is_agent', $is_agent);
        $this->assign('session',session("user_id"));
        $this->display();
    }

    // ajax 拉取子类
    public function ajax_cate_list()
    {
        $shop_id = session('url_shop_id');
        $where = ' status = 1 AND shop_id='.$shop_id;
        if(isset($_POST['pid']) && $_POST['pid'] != ''){
            (I('pid') !== '') && $where = "$where AND pid = ".I('pid');
        }else{
            $pid = M("category")->where("pid = 0 AND status = 1")->order("sort ASC")->field("id")->find();
            $where = "$where AND pid = ".$pid['id'];
        }
        $cateList = M('category')->where($where)->order("sort ASC")->select();
        $this->assign('cateList',$cateList);
        $this->display();
    }


}